Click the button to see the counter increase.
Local storage is great for storing data that you want to
persist across browser sessions.
In order to use local storage with our array, we'll need to convert
our array into a string using a method that makes it easy for us to
unconvert later.
The way convert an array into a string is by using the JSON
stringify function.
Let's say you have the following array called movies:
var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown", "Kill Bill", "Death Proof", "Inglourious Basterds"];
Using the stringify function, your movies array can be turned into a string by using the following syntax:
JSON.stringify(movies)
Since we want to store everything into our local storage, when you put it all together, you get the following:
var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown", "Kill Bill", "Death Proof", "Inglourious Basterds"]; localStorage.setItem("quentinTarantino", JSON.stringify(movies));
Notice that my data is being stored under the key called quentinTarantino.
Storing your data is only part of the fun.
A very important part of
all this is being able to retrieve your data and get back to using it
like an array.
This involves first retrieving your data as a string:
var retrievedData = localStorage.getItem("quentinTarantino");
My retrievedData variable is storing
the values returned by my local storage item whose key is
quentinTarantino.
This data is currently
in the form of a string.
To convert from a string back to an object, use the JSON parse function:
var movies2 = JSON.parse(retrievedData);
Once you have done this, the movies2
variable will point to the parsed data which is, as you can guess, an
array.
You can call all of the array methods on your
movies2 Array object just like you
always would for any old array.
Well, that's all there is to it.
As you can see, the JSON functions
for working with strings makes converting and restoring complex objects
like Arrays really easy.
The technique I've shown here applies equally
to other, non-Array objects as well.
Try it out sometime - it works!
If you have been following along and want to see what my full code looks like, you can find it below:
// our array var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown", "Kill Bill", "Death Proof", "Inglourious Basterds"]; // storing our array as a string localStorage.setItem("quentinTarantino", JSON.stringify(movies)); // retrieving our data and converting it back into an array var retrievedData = localStorage.getItem("quentinTarantino"); var movies2 = JSON.parse(retrievedData); //making sure it still is an array alert(movies2.length);
Notice at the very end I call the length property on the movies2 variable just to ensure that what we have is indeed an array.
HTML5 local storage can be used in applications that need to save user data and preferences across application restarts.
In this article we would be talking about the methods using the local storage to increase the functionality of a web application.
HTML5 local storage is used for storing key value pairs on the client side.
These key value pairs can be retrieved in HTML pages originating from the same domain.
The Local storage data is stored on the disk and persists across application restarts
The Local Storage can be used across applications like gaming, where you save the progress of a game or a store high scores that can be later retrieved OR in Media applications, where an application embeds an audio or video stream, the app can store the timestamp of the audio/video streams in local storage.Since this data is stored across application restarts, you can start the audio/video stream from the last paused location.
The basic methods ( JavaScript* APIs
) for setting and getting item to/from storage are:
// store item
localStorage.setItem("item_key", "value");
// retrieve item
var data = localStorage.getItem("item_key");
Like other JavaScript objects, you can treat the LocalStorage object as an associative array.
Instead of using the getItem()
and setItem()
methods, you can simply use square brackets.
For example, the above snippet of code can also be written as,
// store item
localStorage["item_key"]= value;
// retrieve item
var data = localStorage["item_key"];
Below is the code snippet (from Hangonman game ) which stores and retrieves the game state,
function saveGameState ()
{
localStorage["com.intel.hom.wrongGuesses"] = wrongGuesses;
localStorage["com.intel.hom.rightGuesses"] = rightGuesses;
localStorage["com.intel.hom.word"] = word;
localStorage["com.intel.hom.gameType"] = gameType;
localStorage["com.intel.hom.gameInProgress"] = gameInProgress;
}
function restoreGameState ()
{
if (localStorage && localStorage["com.intel.hom.word"] &&
localStorage["com.intel.hom.gameInProgress"] && (localStorage["com.intel.hom.gameInProgress"] === "true"))
{
wrongGuesses = localStorage["com.intel.hom.wrongGuesses"] || "";
rightGuesses = localStorage["com.intel.hom.rightGuesses"] || "";
word = localStorage["com.intel.hom.word"];
gameType = localStorage["com.intel.hom.gameType"] || 0;
gameInProgress = true;
}
else {
initGameState();
}
}
Unfortunately, present implementations only support string-to-string mappings, so you need to do marshalling to and from strings for other data structures such as an array or JavaScript object.
You can do so by using JSON.stringify()
and JSON.parse()
methods.
var ArrayData = [5, 6, 9];
// store array to localstorage
localStorage.setItem("list_data_key", JSON.stringify(ArrayData));
// retrieve stored data (JSON stringified) and convert
var storedData = localStorage.getItem("ArrayData ");
if (storedData) {
ArrayData = JSON.parse(storedData);
}
Here’s an example restoring the settings, from Hangonman game:
function restoreSettings ()
{
try {
useSounds = JSON.parse(localStorage["com.intel.hom.useSounds"]);
}
catch (e) {
useSounds = true;
localStorage["com.intel.hom.useSounds"] = JSON.stringify(useSounds);
}
}
Other methods that you will probably use are, removeItem
and clear
as below,
// For removing single Key
localStorage.removeItem("item_key"); // where 'item_key' is the key of the value you want to remove
// To clear all Local Storage
localStorage.clear();
For more information on the HTML5 storage APIs, refer to the following resources: